library("foreign")
library("magrittr")
library("dplyr")
library("broom")
library("stringr")
library("knitr")

balance.function.gotv <- function(experiment, vars, define.subset = "!is.na(experiment$id)"){
  data <- subset(experiment, eval(parse(text = define.subset)))
  representativeness.vars <- vars
  x.control <- subset(data, data$treat_string == "GOTV Control", representativeness.vars) #Create data by treatment condition
  x.control <- as.matrix(x.control, dimnames = list(NULL, names(x)))
  x.treat <- subset(data, data$treat_string == "GOTV Treat", representativeness.vars) #Create data by treatment condition
  x.treat <- as.matrix(x.treat, dimnames = list(NULL, names(x)))
  x.placebo <- subset(data, data$treat_string == "GOTV Placebo", representativeness.vars) #Create data by treatment condition
  x.placebo <- as.matrix(x.placebo, dimnames = list(NULL, names(x)))
  control.means <- data.frame(t(colMeans(x.control))) #Calculate means.
  control.means$n <- nrow(x.control)
  treat.means <- data.frame(t(colMeans(x.treat))) #Calculate means.
  treat.means$n <- nrow(x.treat)
  placebo.means <- data.frame(t(colMeans(x.placebo))) #Calculate means.
  placebo.means$n <- nrow(x.placebo)
  means <- rbind(control.means, treat.means, placebo.means)
  row.names(means) <- c("Control", "Treatment", "Placebo")
  means <- t(means)
  #Print
  panderOptions('big.mark', ',')
  panderOptions('table.style','rmarkdown')
  panderOptions('table.alignment.default','right')
  panderOptions('table.alignment.rownames','left')
  panderOptions('digits','2')
  panderOptions('table.caption.prefix','')
  set.caption("**Covariate Balance of Experiment.** Each cell reports the average value of a different covariate at each stage.")
  pander(means, split.tables = 110)
}